package com.mfc.ctrl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mfc.cons.Sys;
import com.mfc.entity.Patient;
import com.mfc.entity.User;
import com.mfc.service.InSupplierService;
import com.mfc.service.PatientService;
import com.mfc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/jsp/supplier")
public class InPatientController {

	@Autowired
	private InSupplierService supplierService;

	@Autowired
	PatientService patientService;

	@Autowired
	UserService userService;


	@RequestMapping("/page")
	public String page(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			, User o, Model model) {

		PageHelper.startPage(pageNo,Sys.pageSize," id desc ");

		List<Patient> li = patientService.list(o);
		PageInfo<Patient> pageInfo=new PageInfo<Patient>(li, Sys.pageSize);

		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("o", o);

		return Sys.jsp+"/supplier_page";
	}


	@RequestMapping("/toedit")
	public String toedit(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,User o,Model model) {
		if(o!=null){
			if (o.getId() != null){
				Patient patient = patientService.selectByUserId(o.getId());
				model.addAttribute("o", patient);
			}
		}
		model.addAttribute("pageNo", pageNo);
		return Sys.jsp+"/supplier_add";
	}

	@RequestMapping("/save")
	public String save(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,Patient o,Model model) {
		User user = new User().setAccount(o.getAccount()).setId(o.getId());
		if(o.getId()!=null){
			userService.updateAccount(user);
			patientService.update(o);
		}else{
			user.setRoleType(3);
			userService.insert(user);
			o.setUserId(user.getId());
			patientService.insert(o);
		}
		return "redirect:/"+Sys.jsp+"/supplier/page?pageNo="+pageNo;
	}


	@RequestMapping("/del")
	public String del(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,User o,Model model) {
		try {
			patientService.delete(o.getId());
			userService.delete(o.getId());
		} catch (Exception e) {

			model.addAttribute("msg", "请先删除该病人关联的其他信息");
			return "forward:/"+Sys.jsp+"/supplier/page?pageNo="+pageNo;
		}
		return "redirect:/"+Sys.jsp+"/supplier/page?pageNo="+pageNo;
	}


	@ResponseBody
	@RequestMapping("/getpage")
	public Object getpage(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,User o,Model model) {
		PageHelper.startPage(pageNo,Sys.pageSize," id desc ");
		List<Patient> li = patientService.list(o);
		PageInfo<Patient> pageInfo=new PageInfo<Patient>(li, Sys.pageSize);

		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("o", o);

		return pageInfo;
	}


}
